<template>
  <div class="container">
    <a-card class="general-card">
      <a-tabs :active-key="areaIndex" class="tab-container" justify @change="onChange">
        <a-tab-pane v-for="(item, idx) in areaData" :key="idx" :title="item.alias">
          <a-space align="center" direction="vertical" size="large" fill>
            <img :src="footballImage" alt="football" style="width: 100px" />
            <a-spin :loading="loading">
              <a-space size="large" align="start">
                <a-badge status="processing" :text="'共 ' + item.x_num + ' 排 ' + item.total_seats + '个座位'" />
                <a-badge status="warning" :text="'不开票 ' + item.unavailable_seats" />
                <a-badge status="processing" :text="'开票 ' + (item.total_seats - item.unavailable_seats)" />
                <a-badge status="success" :text="'已售 ' + item.sold_seats" />
                <a-badge status="normal" text="无座" />
              </a-space>
            </a-spin>
          </a-space>

          <div v-if="idx === areaIndex" class="area-wrap">
            <div class="seat-left">
              <div v-for="(rows, index) in seatData" :key="index" class="x" @click="onReset(index)">
                {{ rows.row }} 排
              </div>
            </div>

            <div class="seat-area" :style="getSeatAreaStyle">
              <div :style="{ width: item.y_num * 40 + 'px' }" style="margin: 0 auto">
                <div v-for="(rows, index) in seatData" :key="index" class="x">
                  <a-space align="center" wrap fill style="justify-content: space-evenly">
                    <template v-for="(column, colIndex) in rows.cols" :key="column.id">
                      <a-popover :title="column.seat_number">
                        <template v-if="column.status === -1">
                          <a-button type="dashed" @click="handleClick(column, index, colIndex)">
                            {{ column.col }}
                          </a-button>
                        </template>
                        <template v-if="column.status === 0">
                          <a-button type="outline" @click="handleClick(column, index, colIndex)">
                            {{ column.col }}
                          </a-button>
                        </template>
                        <template v-if="column.status === 1">
                          <a-button type="primary" status="success" @click="handleClick(column, index, colIndex)">
                            {{ column.col }}
                          </a-button>
                        </template>
                        <template v-if="column.status === 2">
                          <a-button type="primary" status="warning" @click="handleClick(column, index, colIndex)">
                            {{ column.col }}
                          </a-button>
                        </template>
                      </a-popover>
                    </template>
                  </a-space>
                </div>
              </div>
            </div>

            <div class="seat-right">
              <div v-for="(rows, index) in seatData" :key="index" class="x" @click="onDelete(index)">
                {{ rows.row }} 排
              </div>
            </div>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
  // import { useRoute, useRouter } from 'vue-router';
  import { computed, onMounted, onBeforeUnmount, ref } from 'vue';
  import footballImage from '@/assets/football.png';
  import { AreaRecord, SeatRowsRecord, queryAreaList, querySeatList, updateSeatStatus } from '@/api/seat';
  import useLoading from '@/hooks/loading';

  // const route = useRoute();
  // const router = useRouter();

  const { loading, setLoading } = useLoading();

  // 用于记录当前按住的键
  const currentKey = ref('');

  const areaIndex = ref<number>(0);
  const areaData = ref<AreaRecord[]>([]);
  const seatData = ref<SeatRowsRecord[]>([]);

  // 获取区域例表
  const getAreaList = async () => {
    const { data } = await queryAreaList();
    areaData.value = data;
  };

  const updateSeatData = async () => {
    setLoading(true);

    const area = areaData.value[areaIndex.value];
    const { data } = await querySeatList(area.id);
    seatData.value = data;

    setLoading(false);
  };

  const onChange = async (key: string | number) => {
    areaIndex.value = key as number;
    seatData.value = [];
    updateSeatData();
  };

  const handleClick = async (column: any, index: number, colIndex: number) => {
    switch (column.status) {
      case 0:
        column.status = 1;
        break;
      case 1:
        column.status = 2;
        break;
      case 2:
        column.status = -1;
        break;
      default:
        column.status = 0;
        break;
    }

    const ids = [];

    // 对行的批量操作
    if (currentKey.value === 'a' || currentKey.value === 'd') {
      const seatCols = seatData.value[index].cols;
      seatCols.forEach((item: any, key) => {
        if (currentKey.value === 'a') {
          if (colIndex >= key) {
            item.status = column.status;
            ids.push(item.id);
          }
        } else if (colIndex <= key) {
          item.status = column.status;
          ids.push(item.id);
        }
      });
    } else {
      ids.push(column.id);
    }

    // 对例的批量操作
    if (currentKey.value === 'w' || currentKey.value === 's') {
      seatData.value.forEach((item, key) => {
        const col = item.cols[colIndex];
        if (currentKey.value === 'w') {
          if (key <= index) {
            col.status = column.status;
            ids.push(col.id);
          }
        } else if (key >= index) {
          col.status = column.status;
          ids.push(col.id);
        }
      });
    }
    const area = areaData.value[areaIndex.value];

    setLoading(true);
    await updateSeatStatus(area.id, ids, column.status);
    await getAreaList();
    setLoading(false);
  };

  // 恢复一个座位
  const onReset = (column: any) => {
    console.log(column);
    // const index = column.cols
    //   .slice()
    //   .reverse()
    //   .findIndex((item: any) => item.status === 0);
    // if (index !== -1) {
    //   const reverseIndex = column.cols.length - 1 - index;
    //   column.cols[reverseIndex].status = 1;
    // }
  };

  // // 删除一个座位
  const onDelete = (column: any) => {
    console.log(column);
    // const index = column.cols.findIndex((item: any) => item.status !== 0);
    // if (index !== -1) {
    //   column.cols[index].status = 0;
    // }
  };

  // 计算 seat-area 的宽高
  const getSeatAreaStyle = computed(() => {
    const rect = document.body.getBoundingClientRect();
    const width = rect.width - 208;
    const height = rect.height - 280;
    return {
      minWidth: `${width}px`,
      minHeight: `${height}px`,
    };
  });

  function handleKeydown(event: KeyboardEvent) {
    if (currentKey.value !== event.key) {
      currentKey.value = event.key;
    }
  }

  function handleKeyup() {
    currentKey.value = '';
  }

  onMounted(async () => {
    window.addEventListener('keydown', handleKeydown);
    window.addEventListener('keyup', handleKeyup);

    try {
      await getAreaList();
      await updateSeatData();
    } finally {
      setLoading(false);
    }
  });

  onBeforeUnmount(() => {
    window.removeEventListener('keydown', handleKeydown);
    window.addEventListener('keyup', handleKeyup);
  });
</script>

<style lang="less" scoped>
  .container {
    padding: 16px 20px;
  }

  .tab-container {
    :deep(.arco-tabs-nav-tab) {
      justify-content: center;
    }
  }

  .area-wrap {
    display: flex;
    margin-top: 20px;

    .seat-left,
    .seat-right {
      flex: 1;
      gap: 16px;

      .x {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 64px;
        height: 32px;
        margin-bottom: 8px;
        cursor: pointer;
      }
    }

    .seat-area {
      margin: 0 auto;
      overflow: scroll;

      :deep(button) {
        width: 32px;
        height: 32px;
        padding: 0;
      }

      // :deep(.btn-empty) {
      //   color: var(--color-text-4);
      //   background-color: var(--color-neutral-9);
      // }
    }
  }
</style>
